<template>
  <div class="ewe-initial-container">
    <!-- 操作栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="danger" @click="handleSave">
          <el-icon><Document /></el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="danger" @click="handleUndo">
          <el-icon><RefreshLeft /></el-icon>
          <span>撤销</span>
        </el-button>
        <el-button type="danger" @click="handleDelete">
          <el-icon><Delete /></el-icon>
          <span>删除</span>
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-icon class="toolbar-icon"><Setting /></el-icon>
        <el-icon class="toolbar-icon"><Printer /></el-icon>
      </div>
    </div>

    <!-- 信息显示区域 -->
    <div class="info-section">
      <div class="info-item">
        <span class="info-label">期初日期：</span>
        <span class="info-value">{{ initialDate }}</span>
      </div>
      <div class="info-item">
        <span class="info-label">单据号：</span>
        <el-input 
          v-model="documentNumber" 
          placeholder="--" 
          class="info-input"
          disabled
        />
      </div>
      <div class="info-item">
        <span class="info-label">流水号：</span>
        <el-input 
          v-model="serialNumber" 
          placeholder="--" 
          class="info-input"
          disabled
        />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column prop="sequence" label="序号" width="80" align="center" />
        <el-table-column prop="earTag" label="*耳号" align="center">
          <template #default="{ row }">
            <el-select
              v-model="row.earTag"
              placeholder="请选择耳号"
              size="small"
              clearable
              filterable
              :loading="loadingEarTags"
              style="width: 100%"
              @change="(value: string | null) => handleEarTagSelect(value, row)"
            >
              <el-option
                v-for="option in earTagOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="barn" label="*栋舍" align="center" min-width="120">
          <template #default="{ row }">
            <el-input
              v-model="row.barn"
              placeholder="请输入栋舍"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" align="center" min-width="140">
          <template #default="{ row }">
            <el-date-picker
              v-model="row.birthDate"
              type="date"
              placeholder="选择日期"
              size="small"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="geneRank" label="基因等级" align="center" min-width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.geneRank"
              placeholder="请选择基因等级"
              size="small"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="option in geneRankOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="weight" label="重量(公斤)" align="center" min-width="120">
          <template #default="{ row }">
            <el-input
              v-model="row.weight"
              placeholder="请输入重量"
              size="small"
              type="number"
              step="0.01"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部汇总和操作 -->
    <div class="footer-section">
      <div class="footer-left">
        <div class="summary">
          <span class="summary-label">合计：</span>
          <span class="summary-value">{{ totalWeight.toFixed(2) }}</span>
        </div>
        
        <div class="row-actions">
          <el-button type="danger" plain @click="handleAddRow" link>
            <el-icon><Plus /></el-icon>
            <span>增行</span>
          </el-button>
          <el-button type="danger" plain @click="handleDeleteRow" link>
            <el-icon><Minus /></el-icon>
            <span>删行</span>
          </el-button>
        </div>
      </div>

      <div class="footer-right">
        <div class="remarks">
          <span class="remarks-label">备注：</span>
          <el-input
            v-model="remarks"
            placeholder="请输入备注信息"
            class="remarks-input"
            size="small"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated } from 'vue'
import { Plus, Document, RefreshLeft, Delete, Setting, Printer, Minus } from '@element-plus/icons-vue'
import { Reads, Writes } from '@/Utils/axiosHelper'
import axios from 'axios'
import router from '@/router'

// 基本信息
const initialDate = ref('2020-10-20')
const documentNumber = ref('')
const serialNumber = ref('')
const remarks = ref('')

// 耳号选项列表
const earTagOptions = ref<Array<{value: string, label: string}>>([])
const loadingEarTags = ref(false)

// 出生状态选项
const birthStatusOptions = [
  { value: 1, label: '单胎' },
  { value: 2, label: '双胎' },
  { value: 3, label: '三胎' },
  { value: 4, label: '四胎' },
  { value: 5, label: '五胎' },
  { value: 6, label: '六胎' }
]

// 基因等级选项
const geneRankOptions = [
  { value: 1, label: 'A级' },
  { value: 2, label: 'B级' },
  { value: 3, label: 'C级' },
  { value: 4, label: 'D级' }
]

// 表格数据
const tableData = ref([
  {
    sequence: 1,
    earTag: '',
    barn: '',
    birthDate: '',
    geneRank: '',
    weight: ''
  }
])

// 计算总重量
const totalWeight = computed(() => {
  return tableData.value.reduce((sum, row) => {
    const weight = parseFloat(row.weight) || 0
    return sum + weight
  }, 0)
})

// 操作处理
const handleAdd = () => {
  console.log('新增')
}

/**
 * 保存母羊期初数据
 * 按照后端要求格式发送POST请求：
 * {
 *   "DocumentNumber": "string",        // 单据号（已生成）
 *   "InitialGenders": [0],             // 性别数组，种母统一为2
 *   "Note": "string",                  // 备注信息
 *   "SheepIds": [0]                    // 选中的羊只ID数组
 * }
 */
const handleSave = async () => {
  try {
    // 获取所有已选择耳号的行（earTag有值的行）
    // 处理earTag可能是字符串或数字的情况，统一转换为字符串后判断
    const selectedRows = tableData.value.filter(row => {
      const earTagValue = String(row.earTag || '').trim()
      return earTagValue !== '' && earTagValue !== '0'
    })
    
    if (selectedRows.length === 0) {
      console.warn('没有选中的耳号数据，无法保存')
      alert('请先选择耳号再保存')
      return
    }
    
    // 批量获取下拉框value值（耳号ID）
    // 注意：row.earTag可能是字符串或数字，统一转换为整数
    const sheepIds = selectedRows.map(row => {
      const earTagValue = row.earTag
      // 如果已经是数字，直接返回；如果是字符串，先解析
      return typeof earTagValue === 'number' ? earTagValue : parseInt(String(earTagValue))
    }).filter(id => !isNaN(id) && id > 0) // 过滤掉无效ID
    
    if (sheepIds.length === 0) {
      console.warn('没有有效的羊只ID，无法保存')
      alert('请检查耳号数据是否有效')
      return
    }
    
    // 构建请求数据 - 种母的InitialGenders统一为2
    // 数组长度与sheepIds相同，每个元素都是2（表示母羊）
    const requestData = {
      DocumentNumber: documentNumber.value,  // 单据号（自动生成）
      InitialGenders: sheepIds.map(() => 2),  // 种母的性别统一为2（与sheepIds数组长度相同）
      Note: remarks.value || '',  // 备注信息（可选）
      SheepIds: sheepIds  // 选中的羊只ID列表
    }
    
    console.log('准备保存母羊期初数据:', requestData)
    console.log('选中的行数:', selectedRows.length)
    console.log('有效的羊只ID数:', sheepIds.length)
    
    // 发送POST请求保存数据到后端
    const response = await Writes.post('/Management/CreateInitialformBatch', requestData)
    
    console.log('保存响应:', response.data)
    
    // 根据后端返回的状态码判断保存是否成功
    if (response.data && response.data.code === 100) {
      console.log('母羊期初数据保存成功')
      alert('保存成功！')
      router.push('/ewe-initial-list')
    } else {
      console.error('保存失败:', response.data)
      alert('保存失败，请检查控制台日志')
    }
  } catch (error) {
    console.error('保存母羊期初数据失败:', error)
    alert('保存失败，请检查网络连接')
  }
}

const handleUndo = () => {
  console.log('撤销')
}

const handleDelete = () => {
  console.log('删除')
}

const handleAddRow = () => {
  const newRow = {
    sequence: tableData.value.length + 1,
    earTag: '',
    barn: '',
    birthDate: '',
    geneRank: '',
    weight: ''
  }
  tableData.value.push(newRow)
}

const handleDeleteRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
  } else {
    tableData.value[0] = {
      sequence: 1,
      earTag: '',
      barn: '',
      birthDate: '',
      geneRank: '',
      weight: ''
    }
  }
}

// 根据耳号查询母羊详细信息并反填
const fetchEweInfo = async (eweId: number, row: any) => {
  try {
    console.log('查询母羊信息，ID:', eweId)
    const response = await Reads.get('/Management/GetEweFileById', {
      params: {
        EweId: eweId
      }
    })
    
    console.log('母羊查询响应数据:', response.data) // 调试日志
    
    if (response.data && response.data.code === 400) {
      const info = response.data.data
      if (info) {
        // 反填数据到当前行 - 根据实际返回的字段结构（小驼峰格式）
        row.barn = info.placeOfBirth?.toString() || ''  // 出生地作为羊舍
        row.birthDate = info.dateofBirth?.toString() || ''  // 出生日期
        row.geneRank = info.geneRank  // 基因等级
        row.weight = info.birthWeight?.toString() || '' // 出生体重作为重量
        console.log('母羊信息反填成功:', info)
      }
    } else {
      console.error('查询母羊信息失败:', response.data)
    }
  } catch (error) {
    console.error('查询母羊信息失败:', error)
  }
}

// 处理耳号选择事件
const handleEarTagSelect = async (value: string | null, row: any) => {
  // value为null或空字符串时表示取消选择
  const isSelected = !!value
  const eweId = value ? parseInt(value) : (row.earTag ? parseInt(row.earTag) : 0)
  
  if (eweId === 0) return
  
  // 如果选择了耳号，查询详细信息并反填
  if (value) {
    await fetchEweInfo(eweId, row)
  }
  
  try {
    const payload = {
      EweId: eweId,
      Initialstate: isSelected
    }
    
    console.log('发送母羊状态数据:', payload)
    const response = await Writes.put('/Management/UpdateEweInitialstate', payload)
    console.log('母羊状态更新响应:', response.data)
  } catch (error) {
    console.error('更新母羊状态失败:', error)
  }
}

// 获取耳号列表
const fetchEarTagOptions = async () => {
  try {
    loadingEarTags.value = true
    const response = await Reads.get('/Management/GetEweFileMenu')
    
    if (response.data && response.data.code === 400) {
      console.log('母羊响应数据:', response.data)
      const data = response.data.data || []
      // 直接使用返回的数据，它已经包含了value和label字段
      earTagOptions.value = data
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
  } finally {
    loadingEarTags.value = false
  }
}

// 生成单据号和流水号
const generateDocumentNumbers = () => {
  const now = new Date()
  const dateStr = now.toISOString().slice(0, 10).replace(/-/g, '') // YYYYMMDD格式
  const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '') // HHMMSS格式
  
  // 单据号格式：MXQ+日期+时间，如 MXQ20241225143000
  documentNumber.value = `MXQ${dateStr}${timeStr}`
  
  // 流水号格式：当前时间戳后6位，如 14300scripterialNumber.value = `${dateStr.slice(-6)}${timeStr}`
}

// 组件挂载时获取耳号列表
onMounted(() => {
  generateDocumentNumbers()
  fetchEarTagOptions()
})

// 页面刷新时重新生成编号
onActivated(() => {
  generateDocumentNumbers()
})
</script>

<style scoped>
.ewe-initial-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 15px;
}

.toolbar-icon {
  font-size: 18px;
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.toolbar-icon:hover {
  color: #409eff;
}

.info-section {
  display: flex;
  gap: 30px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.info-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.info-input {
  width: 120px;
}

.table-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.footer-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 30px;
}

.footer-left {
  flex: 1;
}

.footer-right {
  flex: 1;
  min-width: 300px;
}

.summary {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.summary-label {
  color: #606266;
  font-size: 14px;
}

.summary-value {
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.row-actions {
  display: flex;
  gap: 15px;
}

.remarks {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.remarks-label {
  color: #606266;
  font-size: 14px;
  white-space: nowrap;
}

.remarks-input {
  flex: 1;
}

/* 按钮样式 */
:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

:deep(.el-button--danger.is-plain) {
  background-color: transparent;
  border-color: #f56c6c;
  color: #f56c6c;
}

:deep(.el-button--danger.is-plain:hover) {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

:deep(.el-button--danger.is-plain.is-link) {
  border: none;
  background: transparent;
  padding: 0;
}

:deep(.el-button--danger.is-plain.is-link:hover) {
  background: #fef0f0;
}

/* 表格样式 */
:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  font-weight: 600 !important;
}

:deep(.el-table td) {
  padding: 10px 0 !important;
}

:deep(.el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.el-input__inner) {
  border: none !important;
  padding: 0 !important;
}

:deep(.el-input__inner:focus) {
  border: 1px solid #409eff !important;
  border-radius: 4px;
  padding: 0 8px !important;
}

/* 日期选择器样式 */
:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  padding: 0 !important;
}

:deep(.el-date-editor .el-input__inner) {
  padding: 0 !important;
}
</style>

